/**
 * 
 */
package com.ubb.smartsearch.web;

import java.util.List;
import java.util.Map;

import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SortOrder;

import com.ubb.smartsearch.controller.SearchHandlerLocal;
import com.ubb.smartsearch.searchengineif.entity.Result;

/**
 * @author Aron
 * 
 */
public class LazyResultDataModel extends LazyDataModel<Result> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private SearchHandlerLocal searchHandler;
	private List<Result> searchResults;

	public LazyResultDataModel(SearchHandlerLocal searchHandler,
		String searchField) {
		this.searchHandler = searchHandler;
		if (searchField != null) {
			this.searchResults = (List<Result>) searchHandler
					.handleSimpleSearch(searchField);
		}
	}

	@Override
	public List<Result> load(int first, int pageSize, String sortField,
			SortOrder sortOrder, Map<String, String> filters) {

		// rowCount
		int dataSize = searchResults.size();
		this.setRowCount(dataSize);

		List<Result> temp = null;
		// paginate
		if (dataSize > pageSize) {
			try {
				temp = searchResults.subList(first, first + pageSize);
			} catch (IndexOutOfBoundsException e) {
				temp = searchResults.subList(first, first
						+ (dataSize % pageSize));
			}
		} else {
			temp = searchResults;
		}

		return searchHandler.classify(temp);
	}

}
